package com.meizu.utils;

import cn.hutool.core.io.FileUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PartUtil{
    String oldName,newName,stoPath,outPath;
    //图片上传必须传图片文件和
    public String uploadImage(Part part,String realPath) throws IOException {
        oldName = part.getSubmittedFileName();//获取文件的原始名字
        if (part.getSize()>0){
            //D:\Java03\YF03405\02Java\code\Java\Git\meizu\out\artifacts\meizu_Web_exploded\
            stoPath=realPath.substring(0,realPath.indexOf("out"))+"web/img/htPhoto/";
            outPath=realPath+"img/htPhoto/";
            //上传头像文件
            newName=uniqeName ()+getSuffix (oldName);
            FileUtil.writeFromStream(part.getInputStream(),stoPath+newName);//
            FileUtil.copyFile(stoPath+newName,outPath+"/"+newName);
        }
        return  "../img/htPhoto/"+newName;
    }

    //获取文件后缀名
    public String getSuffix(String oldName){
        //.png/.jpg……
        int i = oldName.lastIndexOf(".");
        return oldName.substring(i);
    }
    //生成唯一的文件名
    public String uniqeName(){
        //获取当前系统时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String s=sdf.format(date);
        //生成四位数的随机数  1-9999之间，不够四位的，补齐四位 0001  0025
        int rnd = (int)(Math.random()*9999)+1;
        //rnd=4
        String n = rnd+"";
        for(int i=0;i<(4-n.length());i++){
            n="0"+n;
        }
        return s+n;
    }



}
